/*
 * 文件名： AlipayScanPayCmbcSericeImpl.java
 * 
 * 工程名称: bis-service
 *
 * Gopay
 *
 * 创建日期： 2017年1月10日
 *
 * Copyright(C) 2017, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.service.bank.impl.scan;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.manager.bank.scan.AlipayScanPayCmbcManager;
import com.gopay.common.Result;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.alipay.cmbc.AlipayTransMsg;
import com.gopay.common.domain.bank.alipay.cmbc.scan.AlipayQueryBody;
import com.gopay.common.domain.bank.alipay.cmbc.scan.AlipayRefundBody;
import com.gopay.common.domain.bank.alipay.cmbc.scan.AlipayScanPayBody;
import com.gopay.common.domain.bank.wechat.scan.cmbc.FileDownReq;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayResultMsg;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayServerNotifyMsg;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.ScanPayInteractRemoteService;
import com.gopay.remote.bank.ScanPayMerchantService;

/**
 * 支付宝扫码支付业务实现
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2017年1月10日
 */
public class AlipayScanPayCmbcSericeImpl implements ScanPayInteractRemoteService, ScanPayMerchantService {
	/**
	 * 日志对象
	 */
	private static Logger logger = LoggerFactory.getLogger(AlipayScanPayCmbcSericeImpl.class);

	@Resource(name = "alipayScanPayCmbcManager")
	private AlipayScanPayCmbcManager alipayScanPayCmbcManager;

	@Override
	public Result pay(BaseMessage msg) throws GopayException {
		logger.info("------------AlipayScanPayCmbcSericeImpl pay start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result(false);
		try {
			@SuppressWarnings("unchecked")
			AlipayTransMsg<AlipayScanPayBody> resMessage = (AlipayTransMsg<AlipayScanPayBody>) alipayScanPayCmbcManager
					.scanPay(msg);
			logger.info("---支付宝扫码支付民生渠道返回处理对象：" + ToStringBuilder.reflectionToString(resMessage));
			/**
			 * 定义扫码返回对象
			 */
			ScanPayResultMsg respMsg = new ScanPayResultMsg();
			AlipayScanPayBody scanPayResult = (AlipayScanPayBody) resMessage.getBody();
			if (StringUtils.equalsIgnoreCase("R", resMessage.getHead().getRespType())
					&& StringUtils.isNotBlank(scanPayResult.getQrCode())) {
				BeanUtils.copyProperties(resMessage, respMsg);
				/**
				 * 金额精确到元，保留2位小数
				 */
//				respMsg.setAmount(msg.getTotalAmount());
//				respMsg.setGoodsBody(scanPayResult.getDesc());
//				respMsg.setGoodsTag(scanPayResult.getSubject());
				respMsg.setCodeUrl(scanPayResult.getQrCode());
				respMsg.setCodeImage(scanPayResult.getQrCode());

				respMsg.setCode_url(scanPayResult.getQrCode());
				respMsg.setCode_img_url(scanPayResult.getQrCode());

				result.setDefaultModel(respMsg); // 收银台从ScanPayBaseMessage类获取支付请求结果
				result.setSuccess(true);
			} else {
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E1161);
				result.setErrorMsg(resMessage.getHead().getRespMsg());
				result.setSuccess(false);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E1161);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ AlipayScanPayCmbcSericeImpl pay end，耗时(ms):" + (endTime - beginTime));
		return result;

	}

	@Override
	public Result orderQuery(BaseMessage msg) throws GopayException {
		logger.info("------------AlipayScanPayCmbcSericeImpl orderQuery start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result();
		try {
			@SuppressWarnings({ "unchecked" })
			AlipayTransMsg<AlipayQueryBody> resMsg = (AlipayTransMsg<AlipayQueryBody>) alipayScanPayCmbcManager
					.orderQuery(msg);
			logger.info("---支付宝民生扫码订单查询返回处理对象：" + ToStringBuilder.reflectionToString(resMsg));
			if (null == resMsg.getBody().getTotalAmount()) {
				resMsg.setAmount(msg.getAmount());
			} else {
				resMsg.setAmount(resMsg.getBody().getTotalAmount());
			}
			result.setDefaultModel(resMsg);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ AlipayScanPayCmbcSericeImpl orderQuery end，耗时(ms):" + (endTime - beginTime));
		return result;
	}

	@Override
	public Result refund(BaseMessage msg) throws GopayException {
		logger.info("------------AlipayScanPayCmbcSericeImpl refund start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result(false);
		try {
			@SuppressWarnings("unchecked")
			AlipayTransMsg<AlipayRefundBody> resMsg = (AlipayTransMsg<AlipayRefundBody>) alipayScanPayCmbcManager
					.refund(msg);
			if (resMsg != null) {
				if (!"E".equals(resMsg.getHead().getRespType())) {
					result.setDefaultModel(resMsg);
					result.setSuccess(true);
					// 接收成功
					result.setModel("falg", true);
				} else {
					result.setSuccess(false);
					result.setModel("falg", false);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
					result.setErrorMsg(resMsg.getHead().getRespMsg());
				}
			} else {
				result.setSuccess(false);
				result.setModel("falg", false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
			}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ AlipayScanPayCmbcSericeImpl refund end，耗时(ms):" + (endTime - beginTime));
		return result;
	}

	@Override
	public Result refundQuery(BaseMessage msg) throws GopayException {
		logger.info("------------AlipayScanPayCmbcSericeImpl refundQuery start-------------");
		long beginTime = System.currentTimeMillis();
		/**
		 * 定义返回对象
		 */
		Result result = new Result();
		try {
			@SuppressWarnings({ "unchecked" })
			AlipayTransMsg<AlipayQueryBody> resMsg = (AlipayTransMsg<AlipayQueryBody>) alipayScanPayCmbcManager
					.orderQuery(msg);
			logger.info("---支付宝民生扫码订单查询返回处理对象：" + ToStringBuilder.reflectionToString(resMsg));
			if (null == resMsg.getBody().getTotalAmount()) {
				resMsg.setAmount(msg.getAmount());
			} else {
				resMsg.setAmount(resMsg.getBody().getTotalAmount());
			}
			result.setDefaultModel(resMsg);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ AlipayScanPayCmbcSericeImpl orderQuery end，耗时(ms):" + (endTime - beginTime));
		return result;
	}

	@Override
	public Result verify(BaseMessage msg) throws GopayException {
		Result result = new Result(false);
		try {
			@SuppressWarnings("rawtypes")
			AlipayTransMsg verifyMsg = new AlipayTransMsg();
			ScanPayServerNotifyMsg message = (ScanPayServerNotifyMsg) msg;
			BeanUtils.copyProperties(msg, verifyMsg);
			Boolean flag = (Boolean) alipayScanPayCmbcManager.verify(verifyMsg);
			result.setDefaultModel(flag);
			result.setSuccess(true);
			result.setModel("res", message);
			Map<String, String> param = new HashMap<String, String>();
			/**
			 * 验签成功
			 */
			if ((boolean) result.getDefaultModel()) {
				if (("0".equals(message.getPay_result()))) {
					param.put("orderId", message.getOrderId());
					param.put("amt", String.valueOf(message.getAmount()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					param.put("orderId", message.getOrderId());
					param.put("amt", String.valueOf(message.getAmount()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "验签失败");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}
			}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	
	}

	@Override
	public Result merchantSettled(Object msg) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result merchantQuery(Object msg) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result merchantModify(Object msg) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getCheckAccountFile(FileDownReq obj) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result getCheckAlipayAccountFile(FileDownReq obj) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result merchantOperation(Object msg) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result merchantOperationQuery(Object msg) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}
}
